package com.fyx.timedTask;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fyx.config.SecondaryMongoConfig;
import com.fyx.entity.*;
import com.fyx.mapper.*;
import com.fyx.until.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 统计用户
 */
@Slf4j
@Component(value="MatchWinTask")
public class MatchWinTask {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Resource(name = SecondaryMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate secondaryMongoTemplate;

    @Autowired
    private MatchWinEntityMapper matchWinEntityMapper;

    @Autowired
    private TotalTicketLotteryMapper totalTicketLotteryMapper;

    @Autowired
    private SysDictDetailMapper sysDictDetailMapper;

    public void run(){
        Long beginTime=DateUtil.getDayBegin().getTime()/1000;
        long nowTime=new Date().getTime()/1000;
        String tableName=DateUtil.timeStamp2Date(beginTime+"","yyyyMM");;
        if(beginTime==nowTime){
            beginTime=DateUtil.getBeginDayOfYesterday().getTime()/1000;
            if(!DateUtil.timeStamp2Date(beginTime+"","yyyyMM").equals(DateUtil.timeStamp2Date(nowTime+"","yyyyMM"))){
                tableName =DateUtil.timeStamp2Date(beginTime+"","yyyyMM");
            }
        }
        //  beginTime=DateUtil.getBeginDayOfYesterday().getTime()/1000;
        long endTime=beginTime+86400;
        record(beginTime,endTime);
        recordTotal(tableName,beginTime,endTime);
        log.info("用户统计任务：执行完毕=======================");
    }
    private void record(Long beginTime,Long endTime){
        QueryWrapper<SysDictDetail> wrapper1=new QueryWrapper<>();
        wrapper1.eq("dict_id",16);
        wrapper1.eq("dict_sort",900);
        wrapper1.orderByDesc("dict_sort");
        List<SysDictDetail> list1=sysDictDetailMapper.selectList(wrapper1);
        SysDictDetail sysDictDetail1=new SysDictDetail();
        sysDictDetail1.setValue("total");
        sysDictDetail1.setDictSort(99);
        list1.add(sysDictDetail1);
        for(SysDictDetail sysDictDetail:list1){
        MatchWinEntity matchWinEntity=new MatchWinEntity();
        matchWinEntity.setTime(beginTime.intValue());

        if(!sysDictDetail.getValue().equals("total")) {
            matchWinEntity.setChannel("h5" + sysDictDetail.getValue().split("_")[0] + "_wechat");
            matchWinEntity.setFatherChannel("total");
        }else {
            matchWinEntity.setChannel("total");
            matchWinEntity.setFatherChannel("");
        }
        matchWinEntity.setActNum(getActNum(sysDictDetail.getValue(),beginTime,endTime,0));
        matchWinEntity.setMatchNum(getMatchNum(sysDictDetail.getValue(),beginTime,endTime,0));
        matchWinEntity.setLotteryNum(getLotteryNum(sysDictDetail.getValue(),beginTime,endTime,0));

        matchWinEntity.setActNum1(getActNum(sysDictDetail.getValue(),beginTime,endTime,1));
        matchWinEntity.setMatchNum1(getMatchNum(sysDictDetail.getValue(),beginTime,endTime,1));
        matchWinEntity.setTicketNum1(0);
        matchWinEntity.setLotteryNum1(0);

            matchWinEntity.setActNum2(getActNum(sysDictDetail.getValue(),beginTime,endTime,2));
            matchWinEntity.setMatchNum2(getMatchNum(sysDictDetail.getValue(),beginTime,endTime,2));
            matchWinEntity.setTicketNum2(getTicketNum(sysDictDetail.getValue(),beginTime,endTime,2));
            matchWinEntity.setLotteryNum2(getLotteryNum(sysDictDetail.getValue(),beginTime,endTime,2));

            matchWinEntity.setActNum3(getActNum(sysDictDetail.getValue(),beginTime,endTime,3));
            matchWinEntity.setMatchNum3(getMatchNum(sysDictDetail.getValue(),beginTime,endTime,3));
            matchWinEntity.setTicketNum3(getTicketNum(sysDictDetail.getValue(),beginTime,endTime,3));
            matchWinEntity.setLotteryNum3(getLotteryNum(sysDictDetail.getValue(),beginTime,endTime,3));

            matchWinEntity.setActNum4(getActNum(sysDictDetail.getValue(),beginTime,endTime,4));
            matchWinEntity.setMatchNum4(getMatchNum(sysDictDetail.getValue(),beginTime,endTime,4));
            matchWinEntity.setTicketNum4(getTicketNum(sysDictDetail.getValue(),beginTime,endTime,4));
            matchWinEntity.setLotteryNum4(getLotteryNum(sysDictDetail.getValue(),beginTime,endTime,4));

        matchWinEntity.setTicketNum(matchWinEntity.getTicketNum2()+matchWinEntity.getTicketNum3());



        String n="";
        for(int j=1;j<5;j++){
            for(int i=0;i<8;i++) {
               Criteria  criteria=new Criteria();
                criteria.and("time").gte(beginTime).lt(endTime);
                if(!sysDictDetail.getValue().equals("total")) {
                    criteria.and("channel").is("h5" + sysDictDetail.getValue().split("_")[0] + "_wechat");
                }
                criteria.and("place_id").is(j);
                criteria.and("win_turn").is(i);
                Aggregation aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().count().as("v1")
                );
                AggregationResults<StaticeEntity> ar = mongoTemplate.aggregate(aggregation, "turn_match_record", StaticeEntity.class);
                List<StaticeEntity> list = ar.getMappedResults();
                if(list.size()>0){
                    n+=list.get(0).getV1()+",";
                }else {
                    n+="0,";
                }
            }
        }
        matchWinEntity.setSettlement(n);

        QueryWrapper<MatchWinEntity> wrapper=new QueryWrapper<>();
        wrapper.eq("time",beginTime);
        wrapper.eq("channel",matchWinEntity.getChannel());
        MatchWinEntity roomsTurnInfo1=matchWinEntityMapper.selectOne(wrapper);
        if(roomsTurnInfo1==null){
            matchWinEntityMapper.insert(matchWinEntity);
        }
        else {
            matchWinEntityMapper.update(matchWinEntity,wrapper);
        }
        }
    }

    private Integer getActNum(String channel,Long beginTime,Long endTime,Integer placeid){
        Criteria criteria=new Criteria();
        criteria.and("time").gte(beginTime).lt(endTime);
        if(!channel.equals("total")) {
            criteria.and("channel").is("h5" + channel.split("_")[0] + "_wechat");
        }
        if(placeid>0){
            criteria.and("place_id").is(placeid);
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("pid").count().as("v1"),
                Aggregation.group("pid").count().as("v1")

        );
        AggregationResults<StaticeEntity>  ar = mongoTemplate.aggregate(aggregation, "turn_match_record", StaticeEntity.class);
        List<StaticeEntity> list = ar.getMappedResults();
        if(list.size()>0){
          return list.get(0).getV1();
        }
        return  0;

    }

    private Integer getMatchNum(String channel,Long beginTime,Long endTime,Integer placeid) {
        Criteria criteria=new Criteria();
        criteria.and("time").gte(beginTime).lt(endTime);
        if(!channel.equals("total")) {
            criteria.and("channel").is("h5" + channel.split("_")[0] + "_wechat");
        }
        if(placeid>0){
            criteria.and("place_id").is(placeid);
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().count().as("v1")
        );
        AggregationResults<StaticeEntity>  ar = mongoTemplate.aggregate(aggregation, "turn_match_record", StaticeEntity.class);
        List<StaticeEntity> list = ar.getMappedResults();
        if(list.size()>0){
            return list.get(0).getV1();
        }
        return  0;
    }

    private Integer getTicketNum(String channel,Long beginTime,Long endTime,Integer placeid){

        Criteria criteria=new Criteria();
        criteria.and("time").gte(beginTime).lt(endTime);
        if(!channel.equals("total")) {
            criteria.and("channel").is("h5" + channel.split("_")[0] + "_wechat");
        }
        if(placeid>0){
            criteria.and("place_id").is(placeid);
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().count().as("v1")
        );
        AggregationResults<StaticeEntity>  ar = mongoTemplate.aggregate(aggregation, "turn_match_record", StaticeEntity.class);
        List<StaticeEntity> list = ar.getMappedResults();

        if(list.size()>0){
            if(placeid==2) {
                return list.get(0).getV1()*100;
            }else if(placeid==3){
                return list.get(0).getV1()*1000;
            }

        }
        return  0;
    }

    private Integer getLotteryNum(String channel,Long beginTime,Long endTime,Integer placeid){
        Criteria criteria=new Criteria();
        criteria.and("time").gte(beginTime).lt(endTime);
        if(!channel.equals("total")) {
            criteria.and("channel").is("h5" + channel.split("_")[0] + "_wechat");
        }
        if(placeid>0){
            criteria.and("place_id").is(placeid);
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().sum("awards.num").as("v1")
        );
        AggregationResults<StaticeEntity>  ar = mongoTemplate.aggregate(aggregation, "turn_match_record", StaticeEntity.class);
        List<StaticeEntity> list = ar.getMappedResults();
        if(list.size()>0){
            return list.get(0).getV1();
        }
        return  0;
    }

    private void recordTotal(String DataStr,Long beginTime,Long endTime){
        String tableName="props_rec_"+DataStr,n="";
        Integer name=100208;
        QueryWrapper<SysDictDetail> wrapper1=new QueryWrapper<>();
        wrapper1.eq("dict_id",16);
        wrapper1.eq("dict_sort",900);
        wrapper1.orderByDesc("dict_sort");
        List<SysDictDetail> list1=sysDictDetailMapper.selectList(wrapper1);
        SysDictDetail sysDictDetail1=new SysDictDetail();
        sysDictDetail1.setValue("total");
        sysDictDetail1.setDictSort(99);
        list1.add(sysDictDetail1);
        for(int i=0;i<2;i++) {
            for (SysDictDetail sysDictDetail : list1) {
                TotalTicketLottery totalTicketLottery = new TotalTicketLottery();

                totalTicketLottery.setTime(beginTime.intValue());
                if (!sysDictDetail.getValue().equals("total")) {
                    totalTicketLottery.setChannel("h5" + sysDictDetail.getValue().split("_")[0] + "_wechat");
                    totalTicketLottery.setFatherChannel("total");
                } else {
                    totalTicketLottery.setChannel("total");
                    totalTicketLottery.setFatherChannel("");
                }
                if(i==0){
                    name=100206;
                    totalTicketLottery.setFlag("lottery");
                    n=getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, true,27)+",";//7日签到
                    n+=getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, true,54)+",";//对局获得
                    n+=getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, true,83)+",0,";//邀请有礼
                    n+=getMoneyTotals(sysDictDetail.getValue(),beginTime,endTime,1001)+",";
                    n+=getMoneyTotals(sysDictDetail.getValue(),beginTime,endTime,1002)+",";
                    n+=getMoneyTotals(sysDictDetail.getValue(),beginTime,endTime,1003)+",";
                    n+=getMoneyTotals(sysDictDetail.getValue(),beginTime,endTime,1004)+",";
                    n+=getMoneyTotals(sysDictDetail.getValue(),beginTime,endTime,1005)+",";
                    n+=getMoneyTotals(sysDictDetail.getValue(),beginTime,endTime,1006)+",";
                    n+=getMoneyTotals(sysDictDetail.getValue(),beginTime,endTime,1007)+",";
                    n+=getMoneyTotals(sysDictDetail.getValue(),beginTime,endTime,1008)+"";
                }else {
                    name=100208;
                    totalTicketLottery.setFlag("ticket");
                    n=getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, true,27)+",";//7日签到
                    n+=getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, true,54)+",";//对局获得
                    n+=getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, true,83)+",";//邀请有礼
                    n+=getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, true,1)+"";//购买道具赠送
                }
                totalTicketLottery.setTotalNum(getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, true,0));
                totalTicketLottery.setBack(getPropsTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, false,0));
                totalTicketLottery.setPeople(getPeopleTotals(tableName, sysDictDetail.getValue(), beginTime, endTime, name, 0));
                totalTicketLottery.setValueStr(n);

                QueryWrapper<TotalTicketLottery> wrapper=new QueryWrapper<>();
                wrapper.eq("time",beginTime);
                wrapper.eq("channel",totalTicketLottery.getChannel());
                wrapper.eq("flag",totalTicketLottery.getFlag());
                TotalTicketLottery totalTicketLottery1=totalTicketLotteryMapper.selectOne(wrapper);
                if(totalTicketLottery1==null){
                    totalTicketLotteryMapper.insert(totalTicketLottery);
                }
                else {
                    totalTicketLotteryMapper.update(totalTicketLottery,wrapper);
                }
            }
        }
    }

    private Integer getPeopleTotals(String tableName,String channel,Long beginTime,Long endTime,Integer name,Integer way){
        Criteria criteria=new Criteria();
        criteria.and("time").gte(beginTime).lt(endTime);
        criteria.and("name").is(name);
        criteria.and("num").gt(0);
        if(!channel.equals("total")) {
            criteria.and("channel").is("h5" + channel.split("_")[0] + "_wechat");
        }
        if(way>0){
            criteria.and("way").is(way);
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("pid").count().as("v1"),
                Aggregation.group("pid").count().as("v1")
        );
        AggregationResults<StaticeEntity>  ar = secondaryMongoTemplate.aggregate(aggregation, tableName, StaticeEntity.class);
        List<StaticeEntity> list = ar.getMappedResults();
        if(list.size()>0){
            return list.get(0).getV1();
        }
        return  0;
    }

    private Integer getPropsTotals(String tableName,String channel,Long beginTime,Long endTime,Integer name,Boolean isBack,Integer way){
        Criteria criteria=new Criteria();
        criteria.and("time").gte(beginTime).lt(endTime);
        criteria.and("name").is(name);
        if(!channel.equals("total")) {
            criteria.and("channel").is("h5" + channel.split("_")[0] + "_wechat");
        }
        if(isBack){
            criteria.and("num").gt(0);
        }else {
            criteria.and("num").lt(0);
        }
        if(way>0){
            criteria.and("way").is(way);
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().sum("num").as("v1")
        );
        AggregationResults<StaticeEntity>  ar = secondaryMongoTemplate.aggregate(aggregation, tableName, StaticeEntity.class);
        List<StaticeEntity> list = ar.getMappedResults();
        if(list.size()>0){
            return list.get(0).getV1();
        }
        return  0;
    }

    private Integer getMoneyTotals(String channel,Long beginTime,Long endTime,Integer exchangeLv){
        Criteria criteria=new Criteria();
        criteria.and("create_time").gte(beginTime).lt(endTime);
        if(!channel.equals("total")) {
            criteria.and("channel").is("h5" + channel.split("_")[0] + "_wechat");
        }
        if(exchangeLv>0){
            criteria.and("exchangeLv").is(exchangeLv);
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().count().as("v1")
        );
        AggregationResults<StaticeEntity>  ar = mongoTemplate.aggregate(aggregation, "entity", StaticeEntity.class);
        List<StaticeEntity> list = ar.getMappedResults();
        if(list.size()>0){
                return list.get(0).getV1();
        }
        return  0;
    }


}
